![](/img/trans.png)
[英]How to: copying an instance of a class without a proper default constructor; that has members without a default constructor?
[英]C++ Class Constructor Argument: How to access members and methods from another class instance without copying?
我有兩個班級A
和B
在A
,我有一些成員和一些方法,例如,
頭文件:
A.hpp:
class A {
public:
A(int i);
virtual ~A();
int j;
Eigen::Vector3d e;
void printE();
}
B.hpp:
class B
{
public:
B(A* A_ptr);
virtual ~B();
void doSomething();
private:
A * object;
};
源文件:
A.cpp:
#include <iostream>
#include "A.hpp"
using namespace Eigen;
using namespace std;
A::A(int i)
{
j = i;
}
A::~A()
{
}
A::printE()
{
cout<<"e = ("<<this->e(0)<<","<<this->e(1)<<","<<this->e(2)<<")"<<endl;
}
B.cpp:
#include <iostream>
#include "A.hpp"
#include "B.hpp"
using namespace Eigen;
using namespace std;
B::B(const A * A_ptr)
{
object = A_ptr;
}
B::~B()
{
}
B::doSomething()
{
int a = 2*object->j+object->e(1); // very stupid and simple example
}
}
在類B
,我想訪問成員以及A
實例的方法,而不復制任何內容。 我考慮過將指向A
實例的指針傳遞給B
的構造函數,並訪問所需的成員和方法。
上面的代碼只是我問題的抽象,但是希望您能理解我的意思。 我的代碼可以正常編譯(我使用Eclipse Luna),但嘗試創建B
類的實例時除外
#include "A.hpp"
#include "B.hpp"
using namespace Eigen;
using namespace std;
int main(int argc, char **argv)
{
A A_instance(n);
A* A_ptr;
A_ptr = &A_instance;
B B_instance(A_ptr); // commenting this line, the code compiles fine
return 0;
}
編譯此代碼時,Eclipse輸出以下錯誤:
Errors (3 items)
make: *** [all] Error 2
make[1]: *** [some_path.dir/all] Error 2
make[2]: *** [some_other_path] Error 1
不幸的是這對我沒有多大幫助。
我的問題是:哪種方法最好? 使用朋友類或繼承也許更好? (請注意, A
進行了B
所需的一些計算,但它們不相關。)或者在將指針作為B
的構造函數中的參數傳遞時,我做錯了嗎?
void doSomethingB(A_ptr->a);
這不是有效的成員函數聲明,也不是定義。
你可能想寫
void doSomethingB() {
A_ptr->a; // what do you want to do with it?
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.