合成初始化错误

时间:2017-03-07 10:47:25

标签: c++ class inheritance composition

我不断收到错误说:

  

初始化无法转换为' const char *'到地址'

我正在尝试允许Person类在构造函数中使用Address作为参数。我在Address标题文件中包含我的Person标题文件,因此我不知道自己做错了什么。除了调用默认构造函数.cpp之外,我的Person myPerson文件中也没有任何内容。

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

1 个答案:

答案 0 :(得分:-1)

首先重新检查你是否在person类中包含了正确的头文件,我认为你已经包含了可能不是正确文件的“Date.h”,你应该再次检查它。 然后在Person类的构造函数中,您将重新声明已声明为private属性的theAddress Attribute。 它应该是这样的:

   #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) 
   {

   theAddress = ("00","000","00","00");
    cout << "\n The default constructor was called" << endl;
    }

您无法调用构造函数并再次重新声明该属性。 您应该使用构造函数初始化列表来调用Address类的必需构造函数。