转发声明cpp无效使用不完整类型

时间:2016-01-04 12:14:09

标签: c++ forward-declaration

请注意我将这个测试代码写在一个没有头文件的TypeConversion.cpp文件中我正在声明Counter2并尝试在其上调用counter2.getA();这给了我编译时错误无效使用不完整类型'类Counter2'有没有办法解决这个错误? 在.cpp文件中是否有任何转义声明的意义,或仅在头文件中有用。

//TypeConversion.cpp
#include <iostream>
using namespace std;
class Counter2;

class Counter {

public:
int count;


public :
const int* getCount() const{return &(this->count);}

void setCount() {

    this->count=10;

}

// Pre-increment
Counter operator++() {
    this->count++;

    return (*this);
}
//Post increment
Counter& operator++(int){
    Counter dummy;
    dummy.count=this->count;//(*this).n
    this->count++;
    return dummy;
}

 const Counter& modify() {
    this->count=111;
    return *this;
}

Counter()  {
    this->count=0;
    //this->array[5]={1,1,2,3,4};
}

/*Counter(Counter2 &counter2) {
    this->count= counter2.getA() + counter2.getB();
}*/

istream& operator>>(istream& in) {

    in>>this->count;
    return in;
}

void operator=(Counter2 &counter2) {
    this->count = counter2.getA() + counter2.getB();
}

/*  int& operator[](int index){
    return this->array[index];
}*/

};

class Counter2 {
private:
int a ,b;
public:
Counter2() {
    this->a=10;
    this->b=20;
}
Counter2(Counter &c) {
    this->a=c.count;
    this->b=c.count;
}

int getA()  {return this->a;}
int getB()  {return this->b;}

operator Counter() {
    Counter c;
    return c;
}

};

int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
Counter2 c2;
Counter c=c2;
//c=c2;
cout<<endl<<*(c.getCount());
return 0;
}

1 个答案:

答案 0 :(得分:0)

前向声明在头文件中用于例如能够容纳班级的对象。但是一旦你想访问这个类的方法或成员(在你的.cpp中),你必须包含带有定义的正确标题。