如果类划分为单独的文件,则不调用默认构造函数



>更新:

现在我有了这个,它不编译: 啊:

#ifndef A_H
#define A_H
class A {
private:
int foo;
public:
A();
int getfoo();
};
#endif

答.cpp:

#include "A.h"
A::A() {
foo = 5;
}
int A::getfoo(){
return foo;
}

B.h:

#ifndef B_H
#define B_H
class B {
private:
A myA;
public:
B();
int getAvalue();
};
#endif

乙.cpp:

#include "A.h"
#include "B.h"
int B::getAvalue(){
return myA.getfoo();
}

错误:

b.h line 6: C2146: missing ';' before identifier 'myA'
b.h line 6: C4430: missing type specifier - int assumed
b.h line 6: C4430: missing type specifier - int assumed

结束更新

我在不同的 cpp 和头文件中编写了 2 个类:A 类和 B 类。 类 B 使用类 A 作为私有变量,并且从不调用类 A 的默认构造函数。 这是我的代码:

啊:

class A {
public:
A();
int getfoo();
};

答.cpp:

class A {
private:
int foo;
public:
A();
int getfoo();
};
A::A() {
foo = 5;
}
int A::getfoo(){
return foo;
}

B.h:

class B {
public:
int getAvalue();
};

乙.cpp:

#include "A.h"
class B {
private:
A myA;
public:
int getAvalue();
};
int B::getAvalue(){
return myA.getfoo();
}

类测试.cpp:

#include "stdafx.h"
#include <iostream>
#include "B.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
B stackB;
cout << stackB.getAvalue() << endl;
B* storeB = new B();
cout << storeB->getAvalue() << endl;
cin.get();
return 0;
}

输出永远不会为 5,并且永远不会触发构造函数 A::A() 中的断点。我在全球还是本地使用 B 并不重要。如果我将类和函数放在一个文件中,此示例完全可以正常工作。

如果我向类 B 添加一个空的默认构造函数,则会调用类 A 的默认构造函数,但随后 Visual Studio 2008 抱怨变量 stackB 周围的堆栈损坏。

我做错了什么?

仅使用此类:

啊:

class A {
public:
A();
int getfoo();
};

答.cpp:

class A {
private:
int foo;
public:
A();
int getfoo();
};
A::A() {
foo = 5;
}
int A::getfoo() {
return foo;
}

你在A.h中宣布class A.

然后在您的实现 (cpp) 文件中,您再次声明class A. 您也忘记在A.cpp中包含A.h.如果您将标头包含在 cpp 中;编译器会抛出错误,告诉你出了什么问题。您还缺少标头护罩或杂注指令。


您的类应如下所示:

#ifndef A_H
#define A_H
class A {
private:
int foo;
public:
A();
int getFoo() const;  // const to return member and prevents modification
};
#endif // !A_H

答.cpp

#include "A.h" // you forgot to include the header
A::A() : // class constructor using it's member initializer list
foo( 5 ) {
} 
int A::getFoo() const { 
return foo; 
}

现在,一旦你修复了你的类,那么在B类上工作应该不是问题。但是,将一个类的头文件包含在另一个类中时需要注意一件事;您最终可能会得到循环包含。防止这种情况的最佳方法是在标头中使用类原型,并将其标头包含在包含类的 cpp 文件中。在某些情况下,类原型类型不起作用,但我会把它留给你做研究。

如何在C++中使用类原型


B 类可能如下所示:

B.h

#ifndef B_H
#define B_H
// #include "A.h"  // uncomment this if prototype below doesn't work.
class A; // class prototype may not work in all cases;
// If the above prototype does not work; comment it out
// and replace it with #include "A.h".

class B {
private:
A myA;
public:
B(); // remove default
int getAValue() const;
};
#endif // !B_H

B.cpp

#include "B.h"
#include "A.h" // If class A's prototype in the header does not work
// then comment this out and place it in this class B's header by
// replacing it with the prototype.
B::B() {} // default constructor (should make this complete type)
int B::getAValue() const { 
return myA.getFoo(); 
}

这应该有助于解决您的问题。如果使用类原型在标头中不起作用,因为在某些情况下它可能不起作用;可以从标头中删除原型声明,并将其替换为该类的 Include 指令,并从 CPP 文件中删除其 INCLUDE。

最新更新