error C2512: “Name”: 沒有合適的默認構造函數可用


error C2512: “Name”: 沒有合適的默認構造函數可用

 1 #include <iostream>
 2 #include <string>
 3 #include <cmath>
 4 using namespace std;
 5 
 6 class Name
 7 {
 8 public:
 9     Name (char *fst,char * last );
10     //Name (){};
11 string GetName() const ;
12 void setName (const string &fst,const string &last);
13 const string &getFirstName()const {return firstName;}
14 const string &getLastName()const {return lastName;}
15 void print() const ;
16 
17 protected:
18     string firstName; //字符串本身是以字符數組的形式存儲的;
19     string lastName;
20 };
21 Name::Name(char *fst,char * last ):firstName(fst),lastName(last)
22 {
23 }
24 string Name::GetName()const
25 {
26     return (firstName+lastName);
27 }
28 
29 void Name::setName(const string &fst,const string &last)
30 {
31 firstName =fst;
32 lastName =last;
33 }
34 
35 void Name::print()const
36 {
37 cout << firstName <<" "<<lastName<<endl;
38 }
39 
40 class Person 
41 {
42 public :
43 Person (const Name &n, char *paddr,char *pcity,char *pprov,char *zip);
44 void setName(const Name &n);
45 void print() const ;
46 protected:
47     Name name;
48     string addr;
49     string city;
50     string prov;
51     string ZIP;
52 };
53 
54 Person::Person(const Name& n, char *paddr,char *pcity,char *pprov,char *zip)
55 {
56 name =n;
57 addr =paddr;
58 city =pcity;
59 prov =pprov;
60 ZIP =zip;
61 }
62 void Person ::setName(const Name &n)
63 {
64     name.setName(n.getFirstName(),n.getLastName());
65 }
66 void Person::print()const
67 {
68     cout << name.GetName()<<" "<<addr<<" "<<city<<" "<<prov<<" "<<ZIP<<" "<<endl;
69 }
70 int main ()
71 {
72 Person p(Name ("",""),"交大東路1號","大連","遼寧","116026");
73 cout <<"修改名字前:"<<endl;
74 p.print();
75 
76 cout <<"修改名字后:"<<endl;
77 Name n("","");
78 p.setName(n);
79 p.print();
80 return 0;
81 }

1.去掉代碼,出現了如上所示錯誤:

Name (){};

key:由於你在Name中定義了其他構造函數,那么,編譯器不會為你創建默認構造函數;然而,你在Person的構造函數中沒有調用Name的構造函數,那么,編譯器會調用Name的默認構造函數,然而,卻沒有定義,所以,產生了“error C2512: “Name”: 沒有合適的默認構造函數可用”錯誤!

2.#include<string>和#include<cstring>的問題

e:\ccode\test_name\test_name\test.cpp(26): error C2676: 二進制“+”:“const std::string”不定義該運算符或到預定義運算符可接收的類型的轉換
e:\ccode\test_name\test_name\test.cpp(37): error C2679: 二進制“<<”: 沒有找到接受“const std::string”類型的右操作數的運算符(或沒有可接受的轉換)

當為#include<cstring>出現如上兩條錯誤提示;

key:string和CString均是字符串模板類,string為標准模板類(STL)定義的字符串類,已經納入C++標准之中; CString(typedef CStringT > CString)為Visual C++中最常用的字符串類,前者是C++中的標准string類,擁有強大的字符串操作,后者只是C里面的一個庫,功能較弱。STL是標准類模板庫,里面有很多的類,如:vector、map等等。都是一些方便編程的好東西。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM