2013-10-17 4 views
1

회사의 이름과 보고서 이름을 표시하는 프로그램을 작성했지만 다른 사람이 아무 것도 입력하지 않으면 프로그램에서 두 개의 기본 이름을 표시하도록해야합니다. 2 개의 매개 변수로 생성자를 추가해야합니다. 나는 혼란스럽고 점점 더 길을 잃고 있음을 알게됩니다. 내 코드를 교과서 예제처럼 보이도록 만들었지 만 아무 소용이 없습니다. 누군가 포인터와 방향을 알려주시겠습니까?C++ 2 매개 변수 생성자 만들기

Microsoft Visual Studio Express 2012에서 C++을 사용하고 있으며 여기에 현재 코드가 있습니다.

Heading(const char *def_company, const char *def_report) { 
    company = def_company; 
    report = def_report; 
} 

그리고이 (동적 메모리)와 같은 새로운 제목 - 객체를 생성 :

Heading() { 
    company = "Default company"; 
    report = "Default report"; 
} 

당신은이 작업을 수행 할 수 있습니다

//This program displays a company's name and report. 
#include <iostream> 
#include <string> 
using namespace std; 



class Heading 
{ 
private: 
    string company; 
    string report; 

public: 

    void storeInfo (string c, string r); 

    string getCompany() 
    { 
     return company; 
    } 
    string getReport() 
    { 
     return report; 
    } 
}; 

void Heading::storeInfo(string c, string r) 
{ 
company = c; 
report = r; 
} 

void storeInfo(Heading&); 
void showInfo(Heading); 

int main() 
{ 
Heading company; 

storeInfo(company); 
showInfo(company); 

cin.ignore(); 
cin.get(); 

return 0; 
} 

/*****storeInfo*****/ 
void storeInfo(Heading &item) 
{ 
string company; 
string report; 

cout << "\nPlease enter the company name.\n"; 
getline(cin, company); 

cout << "\nPlease enter the report name.\n"; 
getline(cin,report); 

item.storeInfo(company, report); 
} 

/*****showInfo*****/ 
void showInfo(Heading item) 
{ 
cout << item.getCompany() << endl; 
cout << item.getReport(); 
} 
+1

여기에 정의 된 * 생성자가 표시되지 않습니다. 생성자는 클래스와 이름이 같고 반환 유형이 없습니다. – crashmstr

+1

생성자는 어디에 있습니까? –

+0

제목 (string company, string, report)을 수업의 공개 섹션에 추가 하시겠습니까? – Moxy

답변

4

생성자를 만들려면 클래스 내에서이 넣어 :

Heading *object = new Heading("default company", "default report"); 

또는 다음과 같이 (스택에 할당) : 참고로

class Heading 
{ 
    ... 

private: 
    std::string company = "Default"; 
    std::string report = "Default"; 
}; 

:

Heading object("default_company", "default report"); 
+3

본문 안의 멤버에게 할당하지 않고 생성자 이니셜 라이저 목록을 사용하는 것이 좋습니다. 동적 접근 방식을 사용하지 말 것을 강력히 권장합니다.하지만 필요한 경우 스마트 포인터를 사용하십시오. – chris

+2

정적 메모리에서 두 번째 초기화는 어떻게됩니까? –

0

실제로 원하는 것이 분명하지 않습니다. 실제로 생성자를 작성하는 방법을 모르거나 데이터 멤버에 대한 세터가 필요합니다. 쓸 수있는 생성자가 필요한 경우

class Heading 
{ 
private: 
    string company; 
    string report; 
    const char *default_company = "Unknown company"; 
    const char *default_report = "Unknown report"; 

public: 

    Heading(const std::string &company = default_company, const std::string &report = default_report) 
     : company(company), report(report) 
    { 
    } 
    void storeInfo (string c, string r); 

    string getCompany() 
    { 
     return company; 
    } 
    string getReport() 
    { 
     return report; 
    } 
}; 

세터가 필요한 경우 적절하게 이름을 지정하면됩니다. 예를 들어

void storeCompany(const std::string &); 
void storeReport(const std::string &); 

대신 storeInfo가 있습니다.