是否使用“虚拟”对象来促进C ++可接受的OOP,并且存在更好的替代方法吗?

问题描述 投票:0回答:1

我对C ++还是很陌生,在我的教科书中使用用户定义的类进行练习时,我发现创建“虚拟” /“占位符”对象很有帮助,其目的仅仅是为了方便使用函数/ int main()中的向量。我收到的编译器错误指示此类矢量和函数需要附加到类的对象上,因此我创建了一个虚拟对象来满足该需求。

我想知道这是否是可接受的编程实践,或者是否存在更好的替代方法。 (此外,如果此做法比“虚拟对象”更通用,请告诉我。)

我已经包含以下“程序”作为示例。 Food x本身没有任何实际意义;但是,它允许我在“ int main()”中使用“ foodentry()”和“ favoritefoods”向量,因为看来这些项目需要附加到对象上,而“ Food x”是唯一的对象我有。

一如既往地感谢您的输入。

using namespace std;
#include <iostream>
#include <vector>

class Food
{
public:
    string favoritefruit;
    string favoritedessert;
    vector<Food> favoritefoods;
    Food(string a, string b)
        : favoritefruit(a), favoritedessert(b) {}
    void foodentry();
};
//"Placeholder" object. It doesn't do anything except allow me
//to use the function and vector entries in int (main). If I
//don't precede the function and vector entries in int (main)
//with the object x, they show up as undefined. Is there 
//another way to get the function and vector entries in int //main() to work?
Food x{" ", " "};

void Food::foodentry()
{
    cout << "Please enter your favorite fruit, other than oranges:\n";
    cin >> favoritefruit;
    cout << "Now please enter your favorite dessert, other than cookies:\n";
    cin >> favoritedessert;
    favoritefoods.push_back(Food{favoritefruit, favoritedessert});
}

int main()

{
    x.favoritefoods.push_back(Food{"oranges", "cookies"});
    x.foodentry();

    cout << "Here are two great fruits: ";
    for (int y = 0; y < x.favoritefoods.size(); y++)
    {
        cout << x.favoritefoods[y].favoritefruit << " ";
    }
    cout << "\nAnd here are two great desserts: ";
    for (int y = 0; y < x.favoritefoods.size(); y++)
    {
        cout << x.favoritefoods[y].favoritedessert << " ";
    }
}
c++ oop object main
1个回答
1
投票

您需要虚拟对象的事实在某种程度上表明不够理想的类设计。

© www.soinside.com 2019 - 2024. All rights reserved.