代码之家  ›  专栏  ›  技术社区  ›  NaturalDemon

无法使用嵌套类、指针将类型为“test_nested*”的右值(又名“test::test_nester*”)的“test_nest*”类型的变量初始化

  •  0
  • NaturalDemon  · 技术社区  · 10 月前

    我正在尝试访问阵列 *some_nested_array witch是私有嵌套类的一个属性,我还想删除数组的一个指针。

    error indation

    #include <iostream>
    
    class test_nested;
    class test{
    private:
        //public:
        class test_nested{
        public:
            unsigned char array_index;
            unsigned char *some_nested_array;
            test_nested():array_index(10), some_nested_array(new unsigned char[array_index]){
                std::cout << "test_nested created" << std::endl;
                // for(unsigned char i = 0; i != array_index; i++){
                //     //std::cout << "some_array[" << array_index << "]!" << &some_nested_array[i] << std::endl;
                //     std::cout << "some_array: " << &some_nested_array[i] << std::endl;
                // }
            };
            ~test_nested(){};
        };
        test_nested* test_nested_array;
    public:
        test(): test_nested_array(new test_nested[10]){
            std::cout << "test created" << std::endl;
        }
        void remove_Item(unsigned char index){
    
            //free(&this->test_nested_array[index]);
            //delete &this->test_nested_array[index];
            //this->test_nested_array[index] = NULL;
        }
        ~test(){
            delete[] test_nested_array;
        }
    
        //test_nested(* connect(unsigned char index)){
        test_nested* connect(unsigned char index){
            return &this->test_nested_array[index];
        }
    };
    
    int main(int argc, char *argv[])
    {
        test A;
        test_nested *temp = A.connect(6); // error: Cannot initialize a variable of type 'test_nested *' with an rvalue of type 'test_nested *'
    
        // for(unsigned char i = 0; i != array_index; i++){
        //     //std::cout << "some_array[" << array_index << "]!" << &some_nested_array[i] << std::endl;
        //     std::cout << "some_array: " << &some_nested_array[i] << std::endl;
        // }
        A.remove_Item(9);
        //delete A;
        QCoreApplication a(argc, argv);
    
        return -1;
    }
    
    1 回复  |  直到 10 月前
        1
  •  0
  •   Some programmer dude    10 月前

    你有 两个不同 声明 test_nested 结构。

    第一个是您在全局作用域中声明的,它实际上是命名的 ::test_nested 。然后就是你在里面申报的那个 test 类,其名称为 ::test::test_nested (或者只是 test::test_nested 简称)。

    在the main 您使用的功能 *test_nested ,不 测试::test_nested ,这会导致你的错误。

    使用正确的结构,错误应该会消失。