2017-03-02 36 views
0
int main() 
{ 
    string name, sound, owner; 
    int age; 
    int answer = 1; 
    int i = 0; 

    do 
    { 
     ++i; 
     puts("Enter the dog info below"); 
     puts("Dog's name: "); 
     cin >> name; 
     puts("Dog's sound: "); 
     cin >> sound; 
     puts("Dog's age: "); 
     cin >> age; 
     puts("Dog's owner: "); 
     cin >> owner; 

     puts("Do you want to add one more dogs to the database?\n1: Yes\n0:  No"); 
     cin >> answer; 

     Dog name(name, sound, age, owner); 

    } while (answer != 0); 

    for (int a = i; i > 0; i--) 
    { 
     printf("%s", name.getname().c_str()); 
     printf("\n\n%s is a dog who is %d years old, says %s and %s the owner\n\n", 
      name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str()); 
    } 
    return 0; 
} 

這是用於根據用戶輸入創建多個對象的簡單代碼。我設置了類和方法。沒有do while循環,它工作得很好。但我不能根據用戶輸入創建對象並打印它們。以下行顯示錯誤「沒有成員getname」。每個調用的方法都有相同的錯誤。我明白爲什麼會發生這種情況,但有沒有解決方案?如何根據用戶輸入創建和訪問多個對象 - C++

name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str()); 
+0

向我們展示你的'Dog'類。 – user1286901

+0

「我明白爲什麼會發生這種情況」 - 您是否介意解釋爲什麼會發生這種情況以幫助衡量您的知識水平? – immibis

回答

1

您的代碼有一些問題。

第一:你聲明兩個變量在不同的範圍相同的名稱:string namemain()範圍和Dog namedo ... while範圍。 Dog對象只存在於do ... while循環中。當您嘗試在循環外訪問它時,您會收到錯誤... has no member getname,因爲您實際上訪問的是對象string,而不是Dog對象。

第二:您沒有存儲用戶輸入的信息Dog

你需要使用一個向量來存儲Dog對象:

#include <vector> 

int main() 
{ 
    string name, sound, owner; 
    int age; 
    int answer = 1; 
    std::vector<Dog> dogs; // Vector to store Dog objects 

    do 
    { 
     puts("Enter the dog info below"); 
     puts("Dog's name: "); 
     cin >> name; 
     puts("Dog's sound: "); 
     cin >> sound; 
     puts("Dog's age: "); 
     cin >> age; 
     puts("Dog's owner: "); 
     cin >> owner; 

     puts("Do you want to add one more dogs to the database?\n1: Yes\n0:  No"); 
     cin >> answer; 

     Dog dog(name, sound, age, owner); 
     dogs.push_back(dog); // store current dog's info 

    } while (answer != 0); 

    for (int a = 0; a < dogs.size(); a++) 
    { 
     Dog& dog = dogs.at(a); // Get the dog at position i 

     printf("%s", dog.getname().c_str()); 
     printf("\n\n%s is a dog who is %d years old, says %s and %s the owner\n\n", 
      dog.getname().c_str(), dog.getage(), dog.getsound().c_str(), dog.getowner().c_str()); 
    } 
    return 0; 
} 
+0

謝謝你的幫助。 –