【发布时间】:2017-03-07 10:47:24
【问题描述】:
我不断收到错误提示:
初始化无法从 'const char *' 转换为 'Address'
我试图让我的Person 类在构造函数中使用Address 作为参数。我在Person 头文件中包含了我的Address 头文件,所以我不知道我做错了什么。除了调用默认构造函数Person myPerson 之外,我的.cpp 文件中也没有任何内容。
Address头文件:
#ifndef ADDRESSMODEL
#define ADDRESSMODEL
#define ADDRESSDEBUG
#include <iostream>
#include <string.h>
using namespace std;
class Address {
public:
Address(void);
Address(char* aNumber,
char* aStreetName,
char* aTownName,
char* aCounty);
~Address();
void setAddress(char* aNumber,
char* aStreetName,
char* aTownName,
char* aCounty);
char* getNumber(void);
char* getStreetName(void);
char* getTownName(void);
char* getCounty(void);
protected:
private:
char theNumber[4];
char theStreetName[20];
char theTownName[20];
char theCounty[20];
};
inline Address::Address(void) {
char theNumber[] = "0";
char theStreetName[] = "0";
char theTownName[] = "0";
char theCounty[] = "0";
cout << "\n Default constructor was called" << endl;
}
inline Address::Address(char* aNumber,
char* aStreetName,
char* aTownName,
char* aCounty) {
strcpy(theNumber, aNumber);
strcpy(theStreetName, aStreetName);
strcpy(theTownName, aTownName);
strcpy(theCounty, aCounty);
cout << "\n Regular constructor was called" << endl;
}
inline Address::~Address() {
cout << "\n Deconstructor was called" << endl;
}
#endif // ifndef ADDRESSMODEL
我的Person 标头:
#include "Date.h"
#include <iostream>
#include <string.h>
using namespace std;
class Person {
public:
Person(void);
// Person(Address anAddress);
protected:
private:
// Name theName;
// Date theDate;
Address theAddress;
};
inline Person::Person(void) {
Address theAddress = ("00", "000", "00", "00");
cout << "\n The default constructor was called" << endl;
}
// inline Person :: Person(Address anAddress) {
// cout << "\n The regular constructor was called" << endl;
// }
#endif
【问题讨论】:
-
您的代码中有很多错误。宁可使用
std::string而不是char数组。 -
关于您的大量错误,其中之一是
Address默认构造函数没有初始化成员变量。相反,它定义了自己的 local 变量。 -
至于您的问题,请将完整的错误(完整,包括任何可能的信息注释)复制粘贴到问题中作为文本。然后添加例如在您收到错误的行上发表评论。最后是read about the comma operator.
-
好的,感谢@Someprogrammerdude 指出我在默认构造函数中的问题。修复了我几乎所有的错误。
-
你为什么不使用你的构造函数之一来代替 = (...) 的东西呢?那部分是非常难以阅读的。此外,您真的想通过基本教程并从较小的课程开始。让你的代码干净就意味着重写它。如果您希望我这样做,我将在答案中重写您的课程。虽然我只是简单地将 Address 设为一个结构,但我认为没有必要像这样封装一个实际的数据持有者。
标签: c++ class inheritance composition