陈述类a(b)的含义

时间:2011-01-03 11:23:00

标签: c++

我对C ++编程有一点怀疑。

c ++中语句class a(b)的含义是什么,以及如何实现它? 我们可以声明一个这样的类吗?

2 个答案:

答案 0 :(得分:3)

class a(b) 

在C ++中是非法的,会导致编译错误。

我不确定你的意思是什么。也许修改你的问题更具体或包括更多的代码和上下文?

答案 1 :(得分:0)

我同意其他人的意见;看来你有点困惑。让我们看看这是否有帮助。

在C ++类中,a(b)是非法的。但是,如果您希望类a接受参数b,您将在类中创建一个构造函数,如下所示

#include <iostream>
class a
{
    /**
     * Constructors have no type and are setup like a normal function. (They _MUST_
     * have the same name as their class/struct)
     * Generally, the class/struct is located within a ".h" while the actual code
     * is in a corresponding ".cpp" or ".cxx" file. However, in this example
     * I simply combined the class and its code function definitions.
     */
    a(char* b)
    { 
        std::cout<< b << std::endl;
    }
    ~a(){} // Same thing with destructors
};

在这种情况下,参数“b”被定义为char *,因此您将按如下方式初始化此类

int main()
{
    char* bptr = "test_for_pointer"; // Our variable to pass
    char* b = "test_non_pointer";
    a *ptr = new a(bptr); // Pointer declaration
    a tclass(b); // <--- Is this what you were looking to do? 

    // At this point, because of the constructors, both string should have been printed.
    delete ptr; // Clean up the pointer
    ptr = NULL;
    return 0;
}

请注意,在示例中,当声明变量以保存类数据时,我们将其类型声明为“a”并使用“new a()”(如果它是指针)或“VAR_NAME(CONSTRUCTOR_PARAMETERS_LIKE_NORMAL_FUNCTION)”初始化

我希望这有帮助!从C ++开始并不容易 - 你必须做很多阅读,但你会得到它!

祝你好运!
丹尼斯M。

相关问题