Tôi là người mới lập trình bằng C++ với các tệp tiêu đề. Đây là mã hiện tại của tôi:cách liên kết các tệp tiêu đề bằng C++
//a.h
#ifndef a_H
#define a_H
namespace hello
{
class A
{
int a;
public:
void setA(int x);
int getA();
};
}
#endif
//a.cpp
#include "a.h"
namespace hello
{
A::setA(int x)
{
a=x;
}
int A::getA()
{
return a;
}
}
//ex2.cpp
#include "a.h"
#include<iostream>
using namespace std;
namespace hello
{
A* a1;
}
using namespace hello;
int main()
{
a1=new A();
a1->setA(10);
cout<<a1->getA();
return 1;
}
Khi tôi cố gắng biên dịch nó với g++ ex2.cpp
, tôi nhận được lỗi này:
In function `main':
ex2.cpp:(.text+0x33): undefined reference to `hello::A::setA(int)'
ex2.cpp:(.text+0x40): undefined reference to `hello::A::getA()'
collect2: ld returned 1 exit status
Tại sao không cho nó hoạt động, và làm thế nào tôi có thể sửa chữa nó?
Vui lòng sử dụng mã nguồn tính năng định dạng, nhấp vào biểu tượng "101 010" trong trình chỉnh sửa. – mikerobi
Bạn đã quên 'void' trước« A :: setA' trong tệp a.cpp của bạn. –