我们可以将功能分配给cpp中的对象吗?

时间:2018-08-03 18:45:18

标签: c++

class test 
{ 
    int a; 
    static int cnt; 
    public: 
    test() 
    { 
        a=0; 
        cout <<++cnt; 
    } 
    test( int p) 
    { 
        a=p; 
        cout <<++cnt; 
    } 
    ~test() 
    { 
        cout<<cnt--; 
    } 
}; 
int test::cnt; 
void main() 
{ 
    test ob,ob1(10); 
    ob = test(); 
    test(); 
} 

在此代码段中,ob = test();如何为ob分配功能测试。Test是一个类,我们像函数一样调用它。怎么可能

1 个答案:

答案 0 :(得分:0)

函数返回void,对象,对象的引用或指针,这些对象通常可以分配给程序中的变量。在这种特殊情况下,您正在调用测试类对象的构造函数,并且在最终调用中可能遇到未定义的行为。我需要进一步研究可能的UB,自上次阅读以来,C ++标准已更改了两次,VS-2017可能不是最好的oracle,并且我的C ++ foo有点弱。

据我所知,有多种方法可以用C ++初始化对象,而且您的讲师显然已经给您分配了学习第一手的知识。

test ob; // Invokes default constructor on test
test ob(); // Invokes default constructor on test.
test ob = test::test(); // Invokes default constructor on test.

尝试使用代码并输出可用的诊断信息始终是一件好事。我进行了一些调整,以获取更有条理的输出,并强制应用程序在退出之前等待用户输入。您还应该学习使用调试器。您只需单步执行自己的代码,即可学到很多东西。

#include <iostream>
#include <cstdlib>

class test
{
    int a;
    static int cnt;
public:
    test()
    {
        a = 0;
        cnt++;
        std::cout << cnt << std::endl;
    }
    test(int p)
    {
        a = p;
        cnt++;
        std::cout << cnt << std::endl;
    }
    ~test()
    {
        std::cout << cnt << std::endl;
        cnt--;
    }
};
int test::cnt = 0;

int main(void)
{
    {
        test ob; // test::cnt is incremented, 1 is displayed on the console.
        test ob1(10); // test::cnt is incremented, 2 is displayed on the console.
        ob = test::test(); // test::cnt is incremented, 3 is displayed on the console.
        // The following instantiates a temporary test object,
        // the constructor is called, but test::cnt is not incremented on my system.
        // Seems we might be in undefined behavior territory?
        test::test();
    }
    system("pause");
}

请注意,我在'main()'中添加了其他上下文。您不能依靠析构函数在销毁对象的“ main()”结束之后向控制台输出任何内容。将所有对象移到附加的{}上下文中,强制它们在其中构建和销毁,从而使我们能够完整了解控制台输出的情况。

我的Windows框上的上述代码输出为:

1
2
3
3
3
3
2
1
Press any key to continue . . .

我希望计数到4,然后再从4下降。那最后一个电话肯定让我感到困惑。如果没有人给您明确的解释,我会尽快调查。