简体   繁体   English

简化参数传递

[英]Streamlining Parameter Passing

I am reading through Code Complete and had a question about "Streamlining parameter passing".我正在阅读Code Complete并有一个关于“简化参数传递”的问题。 The author says that if you are passing a parameter among several routines, that might indicate a need to factor those routines into a class that share the parameter as class data.作者说,如果您在多个例程之间传递参数,则可能表明需要将这些例程分解为一个类,该类将参数作为类数据共享。

Does this mean that if I have several separate class that use the same data I should create one new class that uses that data and then inherit to make new classes?这是否意味着如果我有几个使用相同数据的单独类,我应该创建一个使用该数据的新类,然后继承以创建新类?

Or或者

Does this mean that if I have a bunch of loose routines in my program I should go ahead and put them into a class and get the benefits of encapsulation, etc.这是否意味着如果我的程序中有一堆松散的例程,我应该继续将它们放入一个类中并获得封装等的好处。

The latter.后者。 It looks like they're talking about a case like this:看起来他们正在谈论这样的案例:

void function_1(std::string& my_data);
void function_2(std::string& my_data);

void main() {
    std::string my_data = "SomeString";
    function_1(my_data);
    function_2(my_data);
}

Which could be changed to:可以改为:

class MyClass {
    std::string my_data;
public:
    MyClass(const std::string& str) : my_data(str) {}
    void function_1();
    void function_2();
}

void main() {
    MyClass obj("SomeString");
    obj.function_1();
    obj.function_2();
}

Where function_1 and function_2 use the my_data field, instead of having to be passed the string every time.其中function_1function_2使用my_data字段,而不必每次都传递字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM