【发布时间】:2012-10-17 19:36:15
【问题描述】:
我正在尝试理解 C++ 中的类并开发一些我在 Python 中看到的类似类。代码如下:
#include <iostream>
#include <cmath>
using namespace std;
/*============================================================================*/
/* Define types
/*============================================================================*/
class none_type;
class bool_type;
class int_type;
struct identifier;
/*============================================================================*/
/* Define none type
/*============================================================================*/
class none_type {
public:
none_type() { /* constructor */ };
~none_type() { /* destructor */ };
}; /* none_type */
/*============================================================================*/
/* Define bool type
/*============================================================================*/
class bool_type {
private:
bool base;
public:
bool_type() { base = false; };
~bool_type() { /* destructor */ };
bool_type(bool init) { base = bool(init); };
bool_type(int init) { base = bool(init); };
bool_type(long init) { base = bool(init); };
bool_type(float init) { base = bool(init); };
bool_type(double init) { base = bool(init); };
bool_type(bool_type init) { base = bool(init.base); };
bool_type(int_type init) { base = bool(init.base); };
int get() { cout << base << endl; };
}; /* bool_type */
/*============================================================================*/
/* Define int type
/*============================================================================*/
class int_type {
private:
long base;
public:
int_type() { base = 0; };
~int_type() { /* destructor */ };
int_type(bool init) { base = long(init); };
int_type(int init) { base = long(init); };
int_type(long init) { base = long(init); };
int_type(float init) { base = long(init); };
int_type(double init) { base = long(init); };
int_type(bool_type init) { base = long(init.base); };
int_type(int_type init) { base = long(init.base); };
int get() { cout << base << endl; };
}; /* int_type */
当我尝试编译它时,g++ 告诉我所有使用我自己的类型的构造函数都是无效的。你能解释一下出了什么问题吗?我已经定义了类原型,我还应该做什么?提前致谢!
【问题讨论】:
-
您不必将
;放在函数定义的末尾。并了解构造函数初始化列表... -
我删除了分号;这解决不了任何问题。似乎在很多情况下您必须在 C/C++ 中删除行尾的分号。
-
您混淆了“定义”和“声明”。
-
您不能在
bool_type类中使用bool_type,因为它还不知道需要多少内存。您需要一个指针或引用才能在其自身中使用该类。 -
删除分号确实解决了一个问题。它有助于使您的程序看起来更专业,这样当其他人阅读您的代码时,他们更有可能相信您知道自己在做什么。它可能无法解决您所问的问题,但这就是弗拉德发表评论而不是回答的原因。
标签: c++ oop class methods constructor