另一个C ++内部的类的调用方法

时间:2019-03-20 13:49:06

标签: c++ visual-studio class methods

我试图为myClass2(作为中间类)的变量myVar(位于myClass1内)设置一个值。但是我得到一个编译错误。 到目前为止,这是我的尝试:

#include <iostream>
using namespace std;
class myClass1{

    int myVar = 5;
    public:
        myClass1();

        myClass1(int x){ myVar = x; }

        int getmyVar(){ return myVar; }
        void setmyVar(int y){ myVar = y; }


};

class myClass2{

    int myScore = 10;
    myClass1 class1;
public:
    myClass2();

    myClass2(int x){ myScore = x; }

    int getmyScore(){ return myScore; }
    void setmyScore(int y){ myScore = y; }
    myClass1 getmyClass1(){ return class1; }


};

int main(){

    myClass2 class2;
    class2.getmyClass1().setmyVar(40);

    return 0;
}

错误是:

Error 1 error LNK2019: unresolved external symbol "public: __thiscall myClass2::myClass2(void)" (??0myClass2@@QAE@XZ) referenced in function _main C:\Users\Ahmed\Desktop\VB\Test2\Test2\Main.obj Test2

1 个答案:

答案 0 :(得分:-2)

查看标记为HERE的更改

#include <iostream>
using namespace std;
class myClass1{

    int myVar = 5;
    public:
    myClass1() {} // HERE

        myClass1(int x){ myVar = x; }

        int getmyVar(){ return myVar; }
        void setmyVar(int y){ myVar = y; }


};

class myClass2{

    int myScore = 10;
    myClass1 class1;
public:
    myClass2() {} // HERE

    myClass2(int x){ myScore = x; }

    int getmyScore(){ return myScore; }
    void setmyScore(int y){ myScore = y; }
    myClass1& getmyClass1(){ return class1; }  // HERE


};

int main(){

    myClass2 class2;
    class2.getmyClass1().setmyVar(40);

    return 0;
}